﻿using Mengsk.ProxyDelivery.Domain;
using Mengsk.ProxyDelivery.Print.Domain;
using Mengsk.ProxyDelivery.Print.Domain.DeliveryNumberGenerator;
using Mengsk.ProxyDelivery.Print.ViewModels;
using Mengsk.ProxyDelivery.Service;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Mengsk.ProxyDelivery.Print.UI
{
    /// <summary>
    /// PrintHistoryUserControl.xaml 的交互逻辑
    /// </summary>
    public partial class PrintHistoryUserControl : UserControl
    {
        private PrintHistoryService printHistoryService = ServiceContainer.GetService<PrintHistoryService>();
        public PrintTemplate[] AllPrintTemplates { get { return new FilePrintTemplateRepertory().GetAll(); } }

        private bool myLoaded = false;

        public PrintHistoryUserControl()
        {
            InitializeComponent();
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            if (this.myLoaded)
            {
                return;
            }
            this.myLoaded = true;
            var list = new List<PrintTemplateCompany>(Domain.PrintTemplateCompanyHelper.GetPrintSupport());
            list.Insert(0, new PrintTemplateCompany { Title = "所有", DeliveryCompany = "" });
            this.cbbDeliveryCompany.ItemsSource = list;
        }

        private void ResetState(IEnumerable<PrintHistoryViewModel> ph)
        {
            foreach (var item in ph)
            {
                item.State = "";
            }
        }

        private PrintHistoryViewModel[] GetSelected(object sender)
        {
            PrintHistoryGroupViewModel vm = (sender as FrameworkElement).Tag as PrintHistoryGroupViewModel;
            PrintHistoryViewModel[] selected = vm.OrderViewModels.Where(obj => obj.IsChecked).ToArray();
            if (selected.Length < 1)
            {
                MessageBox.Show("请选择要相应的打印信息");
            }
            return selected;
        }

        /// <summary>
        /// 修正单号
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAdjustDeliveryNumber_Click(object sender, RoutedEventArgs e)
        {
            PrintHistoryGroupViewModel vm = (sender as Button).DataContext as PrintHistoryGroupViewModel;
            PrintHistoryViewModel[] selected = this.GetSelected(sender);
            if (selected.Length < 1)
            {
                return;
            }

            try
            {
                TextBox tb = ((sender as Button).Parent as StackPanel).FindName("tbNewDeliveryNumber") as TextBox;
                ComboBox cbbDeliveryCompanies = ((sender as Button).Parent as StackPanel).FindName("cbbDeliveryCompanies") as ComboBox;
                string newDeliveryNumber = tb.Text.Trim();
                PrintTemplate pt = cbbDeliveryCompanies.SelectedItem as PrintTemplate;
                if (string.IsNullOrWhiteSpace(newDeliveryNumber) || pt == null)
                {
                    MessageBox.Show("物流公司与快递单号不能为空");
                    return;
                }

                if (selected.Any(obj => obj.Source.PaperType == PaperType.HOT))
                {
                    throw new Exception("电子面单不能修正单号");
                }

                this.ResetState(selected);
                App.DoEvents();
                for (int i = 0; i < selected.Length; i++)
                {
                    selected[i].Background = Brushes.Yellow;
                    selected[i].DeliveryNumber = newDeliveryNumber;
                    selected[i].DeliveryCompany = pt.DeliveryCompany.DeliveryCompany;
                    selected[i].Source.DeliveryNumber = selected[i].DeliveryNumber;
                    selected[i].Source.DeliveryCompany = pt.DeliveryCompany.DeliveryCompany;
                    selected[i].Source.DeliveryTemplateName = pt.Name;
                    selected[i].Source.PrintTime = DateTime.Now;
                    ServiceContainer.GetService<PrintHistoryService>().Update(selected[i].Source.Id, pt.DeliveryCompany.Title, pt.DeliveryCompany.DeliveryCompany, newDeliveryNumber);
                    selected[i].State = "已修正单号";
                    selected[i].Background = null;
                    newDeliveryNumber = DeliveryNumberGeneratorManager.GenenrateNext(pt.DeliveryCompany.Title, newDeliveryNumber).DeliveryNumber;
                    App.DoEvents();
                }
                MessageBox.Show("已完成");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "更新物流单号出错");
            }
        }


        private void btnSearch_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                string sId = this.tbOrderId.Text.Trim();
                string sSellerId = this.tbSellerId.Text.Trim();
                string deliveryNumber = this.tbDeliveryNumber.Text.Trim();
                DateTime startTime = this.dpStart.Value == null ? DateTime.MinValue : this.dpStart.Value.Value;
                DateTime endTime = this.dpEnd.Value == null ? DateTime.MinValue : this.dpEnd.Value.Value;
                long lId = string.IsNullOrWhiteSpace(sId) ? 0 : long.Parse(sId);
                int sellerId = string.IsNullOrWhiteSpace(sSellerId) ? 0 : int.Parse(sSellerId);
                if (lId < 1 && String.IsNullOrWhiteSpace(deliveryNumber) && startTime == DateTime.MinValue)
                {
                    MessageBox.Show("查询信息不能全为空");
                    return;
                }
                var item = ServiceContainer.GetService<PrintHistoryService>().GetByAll(lId, sellerId, this.cbbDeliveryCompany.Text.Trim() == "所有" ? "" : this.cbbDeliveryCompany.Text.Trim(), deliveryNumber, startTime, endTime, 0, 0);
                var group = item.Datas.GroupBy(obj => obj.DeliveryTemplateName);
                var printGroup = group.Select(new Func<IGrouping<string, PrintHistory>, PrintHistoryGroupViewModel>((gs) => new PrintHistoryGroupViewModel(gs.ToArray())));
                this.tcOrderPages.ItemsSource = printGroup;
                if (printGroup.Count() > 0)
                {
                    this.tcOrderPages.SelectedIndex = 0;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void CheckBox_CheckedChanged(object sender, RoutedEventArgs e)
        {
            try
            {
                CheckBox fe = sender as CheckBox;
                if (fe == null)
                {
                    return;
                }

                PrintHistoryGroupViewModel vm = fe.Tag as PrintHistoryGroupViewModel;
                if (vm == null)
                {
                    return;
                }

                foreach (var item in vm.OrderViewModels)
                {
                    item.IsChecked = fe.IsChecked.Value;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }


        private void btnMarkPopDelivery_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var selected = this.GetSelected(sender);
                this.ResetState(selected);
                App.DoEvents();
                foreach (var item in selected)
                {
                    try
                    {
                        item.Background = Brushes.Yellow;
                        item.State = "";
                        this.printHistoryService.MarkPopDelivery(item.Source.Id);
                        item.State = "标记发货成功";
                        item.Background = null;
                    }
                    catch (Exception ex)
                    {
                        item.State = ex.Message;
                        item.Background = Brushes.Red;
                    }
                    finally
                    {
                        App.DoEvents();
                    }
                }
                MessageBox.Show("已完成");
            }
            catch (Exception ex)
            {
                MessageBox.Show("标记发货失败:" + ex.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void btnUpload_Click(object sender, RoutedEventArgs e)
        {
            try
            {

                var printHistorys = this.GetSelected(sender);
                if (printHistorys.Length < 1)
                {
                    return;
                }
                this.ResetState(printHistorys);
                App.DoEvents();
                foreach (var item in printHistorys)
                {
                    this.printHistoryService.Upload(item.Source.Id);
                    item.State = "上传成功";
                    App.DoEvents();
                }
                MessageBox.Show("已完成");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnDelete_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var printHistorys = this.GetSelected(sender);
                if (printHistorys.Length < 1)
                {
                    return;
                }

                if (MessageBox.Show("是否删除打印历史?", "警告", MessageBoxButton.YesNo, MessageBoxImage.Error) != MessageBoxResult.Yes)
                {
                    return;
                }
                this.ResetState(printHistorys);
                App.DoEvents();
                this.printHistoryService.Delete(printHistorys.Select(obj => obj.Source.Id).ToArray());
                foreach (var item in printHistorys)
                {
                    item.State = "已删除";
                }
                App.DoEvents();
                MessageBox.Show("已完成");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnRestPrintState_Click(object sender, RoutedEventArgs e)
        {
            try
            {

                if (MessageBox.Show("是否重置?", "警告", MessageBoxButton.YesNo, MessageBoxImage.Asterisk) != MessageBoxResult.Yes)
                {
                    return;
                }

                OrderService os = ServiceContainer.GetService<OrderService>();
                var printHistorys = this.GetSelected(sender);
                if (printHistorys.Length < 1)
                {
                    return;
                }
                this.ResetState(printHistorys);
                App.DoEvents();
                foreach (var item in printHistorys)
                {
                    try
                    {
                        os.ResetPrintState(item.Source.OrderId);
                        item.State = "重置成功";
                    }
                    catch (Exception ex)
                    {
                        item.State = ex.Message;
                    }
                    App.DoEvents();
                }
                MessageBox.Show("已完成");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void miSelectPre_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                MenuItem mi = sender as MenuItem;
                var datas = mi.DataContext as PrintHistoryGroupViewModel;
                if (datas == null)
                {
                    throw new Exception("没有任何数据");
                }
                var dg = ((ContextMenu)mi.Parent).PlacementTarget as DataGrid;
                var cells = dg.SelectedCells;
                if (cells.Count < 1)
                {
                    return;
                }

                var item = cells[0].Item as PrintHistoryViewModel;
                if (item == null)
                {
                    throw new Exception("数据对象不正确");
                }

                int index = datas.OrderViewModels.IndexOf(item);

                for (int i = 0; i < datas.OrderViewModels.Count; i++)
                {
                    datas.OrderViewModels[i].IsChecked = i <= index ? true : false;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void miSelectForward_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                MenuItem mi = sender as MenuItem;
                var datas = mi.DataContext as PrintHistoryGroupViewModel;
                if (datas == null)
                {
                    throw new Exception("没有任何数据");
                }
                var dg = ((ContextMenu)mi.Parent).PlacementTarget as DataGrid;
                var cells = dg.SelectedCells;
                if (cells.Count < 1)
                {
                    return;
                }

                var item = cells[0].Item as PrintHistoryViewModel;
                if (item == null)
                {
                    throw new Exception("数据对象不正确");
                }

                int index = datas.OrderViewModels.IndexOf(item);

                for (int i = 0; i < datas.OrderViewModels.Count; i++)
                {
                    datas.OrderViewModels[i].IsChecked = i >= index ? true : false;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
    }
}
